package cn.cjgl.controller;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@CrossOrigin
@Controller
@RequestMapping("file")
public class UploadfileController {
	private static final Logger log = LoggerFactory.getLogger(UploadfileController.class);
	
	@RequestMapping(value="uploadFile.do", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> uploadFile(@RequestParam("name") String name,
	        @RequestParam("upload") MultipartFile upload,
	        HttpServletRequest request, HttpServletResponse response){
		log.info("uploadFile");
		
		try {
			String folderPath = request.getSession().getServletContext().getRealPath("")+File.separator+"uploadFile";
			File folder = new File(folderPath);
			if(!folder.exists()) {
				folder.mkdirs();
			}
			String extName = upload.getOriginalFilename().substring(upload.getOriginalFilename().lastIndexOf("."));
			File f = new File(folderPath+File.separator+name+extName);
			log.info(f.getPath());
			byte[] bytes = upload.getBytes();
			log.info("OriginalFileName:"+upload.getOriginalFilename());
			BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(f));
			stream.write(bytes); 
	        stream.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("msg", "上传成功！");
        map.put("success", true);
        return map;
		//return "{\"msg\":\""+"上传成功！"+"\",\"success\":true}";
	}
	
	@RequestMapping(value="showPic.do", method = RequestMethod.POST)
	@ResponseBody
	public String showPic(HttpServletRequest request, HttpServletResponse response){
		return "http://localhost:8090/springboot/static/image/nutcracker.jpg";
	}
	
	@RequestMapping(value="showPicBase64.do", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> showPicBase64(HttpServletRequest request, HttpServletResponse response) throws IOException{
		Map<String, Object> map = new HashMap<String, Object>();
		
		File file = new File(UploadfileController.class.getResource("/").getPath()+"static/image/nutcracker.jpg");
		FileInputStream fis = new FileInputStream(file);
		final ByteArrayOutputStream data = new ByteArrayOutputStream();
		final byte[] by = new byte[1024];
		int len = -1;
        while ((len = fis.read(by)) != -1) {
            data.write(by, 0, len);
        }
        
	    String base64Img = Base64Utils.encodeToString(data.toByteArray());
	    String head = "data:image/jpeg;base64,";  
	    map.put("image", head + base64Img);
	    
	    fis.close();
	    data.close();
	    return map;
	}
	
	@RequestMapping(value="download.do", method = RequestMethod.GET)
	public void download(HttpServletRequest request, HttpServletResponse response) throws IOException{
		
		File file = new File(UploadfileController.class.getResource("/").getPath()+"static/image/nutcracker.jpg");
		FileInputStream fis = new FileInputStream(file);
		ServletOutputStream outputStream = response.getOutputStream();
	    
		response.setHeader("Content-Disposition","attachment;filename=nutcracker.jpg");
		
		final byte[] by = new byte[1024];
		int len = -1;
        while ((len = fis.read(by)) != -1) {
            outputStream.write(by, 0, len);
        }
		
		outputStream.flush();
		outputStream.close();
	    return;
	}

}
